package com.example.mygrade.webapi;

import com.example.mygrade.core.PageUtils;
import com.example.mygrade.core.RUtil;
import com.example.mygrade.domain.Course;
import com.example.mygrade.domain.SC;
import com.example.mygrade.domain.Student;
import com.example.mygrade.domain.TeacherMa;
import com.example.mygrade.intercepter.GlobalConstant;
import com.example.mygrade.service.SCService;
import com.example.mygrade.service.StudentService;
import com.example.mygrade.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {
    @Autowired
    private StudentService studentService;

    @Resource
    private SCService scService;
    /**
     * 读取学生信息
     * @return
     */
    @GetMapping("/list")
    public R getAll() throws Exception{
        List<Student> students = studentService.findAll();

        return RUtil.success(students,"获取成功");
    }

    /**
     * 通过名字进行查询/webapi/student/getList
     * @param name
     * @return
     */
    @GetMapping("/getList/{name}")
    public Student getList(@PathVariable String name){
        Student student1 = studentService.findBySnameLike(name);
        return student1;
    }
    /**
     * 读取的url:/webapi/student/get
     * @return
     */
    @GetMapping("/get/{id}")
    public R get(@PathVariable Integer id){
        Student student = studentService.findById(id);
        student.setPassword("");
        return RUtil.success(student,"获取成功");
    }

    // 封装插入
    /**
     * 新增学生的方法/webapi/student/insert
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public R insert(Student student){
        Student student1 = studentService.insert(student);
        return RUtil.success(student1,"插入成功");
    }

    /**
     * 更新学生的方法/webapi/student/update
     * @param student
     * @return
     */
    @PutMapping("/update")
    public R update(Student student){
        Student oldstudent = studentService.findById(student.getId());

        if (ObjectUtils.isEmpty(student.getPassword())){
            student.setPassword(oldstudent.getPassword());
        }
        Student student1 = studentService.update(student);
        return RUtil.success(student1,"更新成功");
    }


    /**
     * 删除学生的方法/webapi/student/delete
     * @param id
     */
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id){

        studentService.delete(id);
        return RUtil.success(null,"删除成功");
    }

    /**
     * 批量删除学生
     * @param arr
     */
    @DeleteMapping("/batchdelete/{arr}")
    public R delete(@PathVariable Integer[] arr){

        studentService.delete(arr);
        return RUtil.success(null,"批量删除成功");
    }

    /**
     * 学生信息，选择查询
     * @param page
     * @param size
     * @param passage
     * @param chooseQuery
     * @param sortPassage
     * @param direct
     * @return
     */
    @GetMapping("/getbypage")
    public R getByPage(@RequestParam(value = "page",defaultValue = "0")Integer page,
                       @RequestParam(value = "size",defaultValue = "10")Integer size,
                       @RequestParam(value = "passage",defaultValue = "") String passage,
                       @RequestParam(value = "chooseValue",defaultValue = "") String chooseQuery,
                       @RequestParam(value = "sort",defaultValue = "id") String sortPassage,
                       @RequestParam(value = "direct",defaultValue = "ASC") String direct
                               ){
        Page<Student> studentPage;
        Sort sort;
        if (direct.equals("asc")){
            sort = Sort.by(Sort.Direction.ASC,sortPassage);
        }else{
            sort = Sort.by(Sort.Direction.DESC,sortPassage);
        }

        if(ObjectUtils.isEmpty(passage)){
            Pageable pageable = PageRequest.of(page,size,sort);
            studentPage = studentService.findAll(pageable);
        }else {
            switch (chooseQuery) {
                case "1": {
                    Student student = new Student();
                    student.setSno(passage);
                    Pageable pageable = PageRequest.of(page, size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            .withMatcher("sno", ExampleMatcher.GenericPropertyMatchers.contains());
                    Example<Student> example = Example.of(student, matcher);
                    studentPage = studentService.findAll(example, pageable);
                    break;
                }
                case "2": {
                    Student student = new Student();
                    student.setSname(passage);
                    Pageable pageable = PageRequest.of(page, size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            .withMatcher("sname", ExampleMatcher.GenericPropertyMatchers.contains());
                    Example<Student> example = Example.of(student, matcher);
                    studentPage = studentService.findAll(example, pageable);
                    break;
                }
                case "3": {
                    Student student = new Student();
                    student.setSex(passage);
                    Pageable pageable = PageRequest.of(page, size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            .withMatcher("sex", ExampleMatcher.GenericPropertyMatchers.contains());
                    Example<Student> example = Example.of(student, matcher);
                    studentPage = studentService.findAll(example, pageable);
                    break;
                }
                case "4": {
                    Student student = new Student();
                    student.setSage(Integer.parseInt(passage));
                    Pageable pageable = PageRequest.of(page, size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            .withMatcher("sage", ExampleMatcher.GenericPropertyMatchers.contains());
                    Example<Student> example = Example.of(student, matcher);
                    studentPage = studentService.findAll(example, pageable);
                    break;
                }
                case "5": {
                    Student student = new Student();
                    student.setClassid(Integer.parseInt(passage));
                    Pageable pageable = PageRequest.of(page, size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            .withMatcher("classid", ExampleMatcher.GenericPropertyMatchers.contains());
                    Example<Student> example = Example.of(student, matcher);
                    studentPage = studentService.findAll(example, pageable);
                    break;
                }
                case "6": {
                    Student student = new Student();
                    student.setGradeid(Integer.parseInt(passage));
                    Pageable pageable = PageRequest.of(page, size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            .withMatcher("gradeid", ExampleMatcher.GenericPropertyMatchers.contains());
                    Example<Student> example = Example.of(student, matcher);
                    studentPage = studentService.findAll(example, pageable);
                    break;
                }
                default: {
                    Student student = new Student();
                    student.setMid(passage);
                    Pageable pageable = PageRequest.of(page, size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            .withMatcher("mid", ExampleMatcher.GenericPropertyMatchers.contains());
                    Example<Student> example = Example.of(student, matcher);
                    studentPage = studentService.findAll(example, pageable);
                    break;
                }
            }

        }

        PageUtils pageUtils = new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return RUtil.success(pageUtils,"获取成功");
    }


    /**
     * 分页读取全部内容
     * @return
     */
    @GetMapping("/getbypage1")
    public R getByPage1(@RequestParam(value = "page",defaultValue="0") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               @RequestParam(value = "sname",defaultValue = "") String sname,
                               @RequestParam(value = "sex",defaultValue = "") String sex,
                        @RequestParam(value = "sort",defaultValue = "id") String sortPassage,
                        @RequestParam(value = "direct",defaultValue = "ASC") String direct
    ){
        Page<Student> studentPage;
        Sort sort;
        if (direct.equals("asc")){
            sort = Sort.by(Sort.Direction.ASC,sortPassage);
        }else{
            sort = Sort.by(Sort.Direction.DESC,sortPassage);
        }
        if(ObjectUtils.isEmpty(sname)  && ObjectUtils.isEmpty(sex)){
            Pageable pageable = PageRequest.of(page,size, sort);
            studentPage = studentService.findAll(pageable);
        }else if(ObjectUtils.isEmpty(sname) && !ObjectUtils.isEmpty(sex)){
            Student student = new Student();
            student.setSex(sex);
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对性别的精确查询
                    .withMatcher("sex",ExampleMatcher.GenericPropertyMatchers.exact())
                    ;
            Example<Student> example = Example.of(student,matcher);
            studentPage = studentService.findAll(example,pageable);
        }else if(!ObjectUtils.isEmpty(sname) && ObjectUtils.isEmpty(sex)){
            Student student = new Student();
            student.setSname(sname);
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对姓名的模糊查询
                    .withMatcher("sname",ExampleMatcher.GenericPropertyMatchers.contains())
                    ;
            Example<Student> example = Example.of(student,matcher);
            studentPage = studentService.findAll(example,pageable);
        }
        else{
            Student student = new Student();
            student.setSname(sname);
            student.setSex(sex);
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对姓名的模糊查询
                    .withMatcher("sname",ExampleMatcher.GenericPropertyMatchers.contains())
                    //对性别的精确查询
                    .withMatcher("sex",ExampleMatcher.GenericPropertyMatchers.exact())
                    ;
            Example<Student> example = Example.of(student,matcher);
            studentPage = studentService.findAll(example,pageable);
        }

        PageUtils pageUtils = new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return RUtil.success(pageUtils,"获取成功");
    }

    /**
     * 根据session获取学生信息
     * @param page
     * @param size
     * @param httprequest
     * @return
     */
    @GetMapping("/getbystudent")
    public R getByStudent(@RequestParam(value = "page",defaultValue="0") Integer page,
                       @RequestParam(value = "size",defaultValue = "10") Integer size,
                       @RequestParam(value = "passage",defaultValue = "") String passage,
                       @RequestParam(value = "chooseValue",defaultValue = "") String chooseQuery,
                       @RequestParam(value = "sort",defaultValue = "id") String sortPassage,
                       @RequestParam(value = "direct",defaultValue = "ASC") String direct,
                       HttpServletRequest httprequest
    ){
        Page<SC> scPage;
        Sort sort;
        if (direct.equals("asc")){
            sort = Sort.by(Sort.Direction.ASC,sortPassage);
        }else{
            sort = Sort.by(Sort.Direction.DESC,sortPassage);
        }

        HttpSession session = httprequest.getSession();
        Object obj = session.getAttribute(GlobalConstant.USER_SESSION_KEY.getMsg());
        Student student = (Student) obj;
        String sno = student.getSno();
        List<SC> sc1= scService.findBySno(sno);


        if (ObjectUtils.isEmpty(passage)){
            SC sc = new SC();
            sc.setSno(sc1.get(0).getSno());
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对姓名的精确查询
                    .withMatcher("sno",ExampleMatcher.GenericPropertyMatchers.exact());
            Example<SC> example = Example.of(sc,matcher);
            scPage = scService.findAll(example,pageable);
        }else{
            switch (chooseQuery) {
                case "1": {
                    SC sc = new SC();
                    sc.setSno(sc1.get(0).getSno());
                    sc.setCno(sc1.get(0).getCno());
                    Pageable pageable = PageRequest.of(page,size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            //对姓名的精确查询
                            .withMatcher("cno",ExampleMatcher.GenericPropertyMatchers.exact())
                            .withMatcher("sno",ExampleMatcher.GenericPropertyMatchers.exact());
                    Example<SC> example = Example.of(sc,matcher);
                    scPage = scService.findAll(example,pageable);
                    break;
                }
                case "2": {
                    SC sc = new SC();
                    sc.setSno(sc1.get(0).getSno());
                    sc.setCname(sc1.get(0).getCname());
                    Pageable pageable = PageRequest.of(page,size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            //对姓名的精确查询
                            .withMatcher("cname",ExampleMatcher.GenericPropertyMatchers.exact())
                            .withMatcher("sno",ExampleMatcher.GenericPropertyMatchers.exact());
                    Example<SC> example = Example.of(sc,matcher);
                    scPage = scService.findAll(example,pageable);
                    break;
                }
                default: {
                    SC sc = new SC();
                    sc.setSno(sc1.get(0).getSno());
                    sc.setScore(Integer.parseInt(passage));
                    Pageable pageable = PageRequest.of(page,size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            //对姓名的精确查询
                            .withMatcher("score",ExampleMatcher.GenericPropertyMatchers.exact())
                            .withMatcher("sno",ExampleMatcher.GenericPropertyMatchers.exact());
                    Example<SC> example = Example.of(sc,matcher);
                    scPage = scService.findAll(example,pageable);
                    break;
                }
            }
        }
        PageUtils pageUtils = new PageUtils(scPage.getContent(),scPage.getTotalElements());
        return RUtil.success(pageUtils,"获取成功");
    }

    /**
     * excel导入数据
     * @param file
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/importStudent")
    @ResponseBody
    public R importStudent(@RequestParam MultipartFile[] file, HttpSession session) throws Exception{
        int result = 0;
        try {
            result = studentService.insertStudent(file[0]);
        }catch (Exception e){
            e.printStackTrace();
        }

        if (result > 0){
            return RUtil.success(result,"导入成功");
//            return "{\"result\":\"excel文件数据导入成功！\"}";
        }else{
//            return "{\"result\":\"excel文件数据导入失败！\"}";
            return RUtil.error(400,"导入失败");
        }
    }

    /**
     * 更改学生密码
     * @param userName
     * @param oldpassword
     * @param newpassword
     * @return
     */
    @PostMapping("/updatepass")
    public R changePass(String userName,String oldpassword,String newpassword){
        Student student = studentService.findBySnameLike(userName);
        if (student == null){
            return RUtil.error(500,"用户不存在！");
        }
        if (!oldpassword.equals(student.getPassword())){
            return RUtil.error(400,"旧密码错误");
        }
        student.setPassword(newpassword);
        Student student1 = studentService.update(student);
        return RUtil.success(student1,"密码修改成功");
    }

    /**
     * 更改学生个人信息
     * @param sname
     * @param sex
     * @param sage
     * @param httprequest
     * @return
     */
    @PostMapping("/updateper")
    public R changeInfo(String sname,String sex,String sage,HttpServletRequest httprequest){
        HttpSession session = httprequest.getSession();
        Object obj = session.getAttribute(GlobalConstant.USER_SESSION_KEY.getMsg());
        Student student = (Student) obj;
        student.setSname(sname);
        student.setSex(sex);
        student.setSage(Integer.parseInt(sage));

        Student student1 = studentService.update(student);
        return RUtil.success(student1,"更改成功");
    }

    /**
     * 更改之前获取学生信息
     * @param httprequest
     * @return
     */
    @GetMapping("/queryinfo")
    public R queryInfo(HttpServletRequest httprequest){
        HttpSession session = httprequest.getSession();
        Object obj = session.getAttribute(GlobalConstant.USER_SESSION_KEY.getMsg());
        Student student = (Student) obj;
        return RUtil.success(student,"获取成功");
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @PostMapping("/resetpass/{id}")
    public R resetPass(@PathVariable Integer id){
        Student student = studentService.findById(id);
        student.setPassword("123456");
        Student student1 = studentService.update(student);
        return RUtil.success(student1,"重置成功");
    }
}
